import server from "server.js"
import Toast from '../assets/framework/vant/toast/toast';

// 通用 http 请求
const http = ({
  url,
  data = {},
  header = {},
  method = 'GET',
  dataType = 'json'
}) => {
  return new Promise((resolve, reject) => {
    const access_token = {}

    let storageToken = wx.getStorageSync('access_token');
    if (storageToken) {
      access_token['access_token'] = storageToken;
    }

    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    });

    wx.request({
      url,
      data,
      header: {
        ...access_token,
        ...header
      },
      method,
      dataType,
      success(res) {
        Toast.clear();
        if (res.data.code == 0) {
          resolve(res.data.data);
        } else {
          Toast(res.data.msg || '请求出错');
          resolve();
        }
      },
      fail(res) {
        Toast('请求失败');
        reject(res)
      }
    })
  })
}

// GET 类型请求
const get = ({
  url,
  data = {},
  header = {},
  method = 'GET'
}) => {
  return http({
    url: `${server}/${url}`,
    data,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      ...header
    },
    method
  })
}

// POST 类型请求
const post = ({
  url,
  data = {},
  header = {},
  method = 'POST'
}) => {
  return http({
    url: `${server}/${url}`,
    data,
    header: {
      'content-type': 'application/json',
      ...header
    },
    method
  })
}

// 上传文件方法
const upload = ({
  url,
  filePath,
  name = 'file',
  header,
  formData = {}
}) => {
  const access_token = {}

  let storageToken = wx.getStorageSync('access_token');
  if (storageToken) {
    access_token['access_token'] = storageToken;
  }

  Toast.loading({
    message: '上传中...',
    forbidClick: true,
    duration: 0
  });

  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: `${server}/${url}`,
      filePath,
      name,
      header: {
        'content-type': 'multipart/form-data',
        ...access_token,
        ...header,
      },
      formData,
      success (res) {
        Toast.clear();
        resolve(res)
      },
      fail (res) {
        Toast("上传失败");
        reject(res)
      }
    })
  })
}

export default {
  get,
  post,
  upload
}